package com.siao.example.socket;

import java.nio.ByteBuffer;

import com.siao.net.socket.IDataPack;
import com.siao.net.socket.IDataResolver;

public class DataResolver implements IDataResolver {

	public static final Integer HEADER_SIZE = 8;

	@Override
	public boolean isContains(ByteBuffer buffer) {
		if (buffer.remaining() < HEADER_SIZE) {
			return false;
		}

		int position = buffer.position();
		buffer.getInt(); // get type

		int length = buffer.getInt();
		int body = buffer.remaining();

		buffer.position(position);

		return body >= length;
	}

	@Override
	public IDataPack parse(ByteBuffer buffer) {
		int type = buffer.getInt();
		int length = buffer.getInt();

		byte[] body = new byte[length];
		buffer.get(body, 0, length);

		return new DataPack(type, body);
	}

	@Override
	public ByteBuffer pack(IDataPack data) {
		DataPack pack = (DataPack) data;
		ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE + pack.getBody().length);

		buffer.putInt(pack.getType());
		buffer.putInt(pack.getBody().length);
		buffer.put(pack.getBody());

		return buffer;
	}

}
